import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image
import os
import requests
import base64
import time

# 新建屏幕
window = tk.Tk()
# 控制窗口大小
window.geometry('1517x738')
# 禁止窗口拉伸
window.resizable(0, 0)
# 加载图片
bg = ImageTk.PhotoImage(file='people_face_testing/Template.png')
choose_image_button = ImageTk.PhotoImage(file='people_face_testing/choose_image_button.png')
# 获取信息
data_people = {}
# 点击次数
click_num = 0


# 创建壁纸标签
def fn(event):
    print(f'坐标{event.x}, {event.y}')
bgLabel = tk.Label(window, image=bg)
bgLabel.pack()
bgLabel.bind('<Button -1>', fn)


# 图片缩放尺寸方法
def resize( w, h, new_w, new_h, pil_image):
    f1 = 1.0 * new_w / w
    f2 = 1.0 * new_h / h
    factor = min([f1, f2])
    width = int(w * factor)
    height = int(h * factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)


# 显示图片
def showPhoto(route,xPos,yPos):
    #获取图片
    image = Image.open(route)
    #获取原图片尺寸
    w, h = image.size
    #重置尺寸
    resized = resize(w, h, 549, 687, image)
    #展示图片
    photo = ImageTk.PhotoImage(resized)
    photoLabel = tk.Label(window, image=photo)
    photoLabel.place(x=xPos, y=yPos)
    window.mainloop()


# 定义写字方法
def write(text, x, y):
    textLabel = tk.Label(window, text=text, font=('Airal', 26))
    textLabel.place(x=x, y=y)


# 新建选择图片方法
def select_photo():
    global click_num
    click_num += 1
    if click_num >= 2:
        messagebox.showwarning(title='警告', message='已经选择图片，请勿再次选择')
    else:
        time.sleep(2)
        photo = filedialog.askopenfilename(initialdir='c:/', title='chooseImage')
        # 分割文件名字和后缀判断是否是图片类型
        if os.path.splitext(photo)[1] not in ['.png', '.jpg', '.jpeg', '.PNG', '.JPG', '.JPEG'] or len(photo) < 1:
            messagebox.showwarning(message='错误', title='警告')
        else:
            host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=zZeG8xxXGQ0L6dvz6K4kqywI&client_secret=zlbT0qtEhcmNFQ54p2FAXcFfu1tELGtM'
            response = requests.get(host)
            content = response.json()
            # if response:
            #     print(response.json())
            with open(photo, 'rb') as f:
                temp = f.read()
                image = base64.b64encode(temp)
            request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
            params = {'image': image, 'image_type': 'BASE64', 'face_field': 'age,expression,face_shape,gender,glasses,emotion,face_type'}
            access_token = content['access_token']
            request_url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/json'}
            response = requests.post(request_url, data=params, headers=headers)
            content = response.json()
            age = content['result']['face_list'][0]['age']
            data_people['age'] = age
            expression = content['result']['face_list'][0]['expression']['type']
            if expression == 'none':
                expression = '正常'
            elif expression == 'smile':
                expression = '微笑'
            elif expression == 'laugh':
                expression = '大笑'
            data_people['expression'] = expression
            face_shape = content['result']['face_list'][0]['face_shape']['type']
            # square: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形
            if face_shape == 'square':
                face_shape = '正方脸'
            elif face_shape == 'triangle':
                face_shape = '三角脸'
            elif face_shape == 'oval':
                face_shape = '椭圆脸'
            elif face_shape == 'heart':
                face_shape = '心脸'
            elif face_shape == 'round':
                face_shape = '圆脸'
            data_people['face_shape'] = face_shape
            gender = content['result']['face_list'][0]['gender']['type']
            # male:男性 female:女性
            if gender == 'male':
                gender = '男生'
            elif gender == 'female':
                gender = '女生'
            data_people['gender'] = gender
            glasses = content['result']['face_list'][0]['glasses']['type']
            # none:无眼镜，common:普通眼镜，sun:墨镜
            if glasses == 'none':
                glasses = '没带眼镜'
            elif glasses == 'common':
                glasses = '带了普通眼睛'
            elif glasses == 'sun':
                glasses == '带了墨镜'
            data_people['glasses'] = glasses
            emotion = content['result']['face_list'][0]['emotion']['type']
            	# angry:愤怒 disgust:厌恶 fear:恐惧 happy:高兴 sad:伤心 surprise:惊讶 neutral:无表情 pouty: 撅嘴 grimace:鬼脸
            if emotion == 'angry':
                emotion = '愤怒'
            elif emotion == 'disgust':
                emotion = '厌恶'
            elif emotion == 'fear':
                emotion = '恐惧'
            elif emotion == 'happy':
                emotion = '高兴'
            elif emotion == 'sad':
                emotion = '伤心'
            elif emotion == 'surprise':
                emotion = '惊讶'
            elif emotion == 'neutral':
                emotion = '正常'
            elif emotion == 'pouty':
                emotion = '撅嘴'
            elif emotion == 'grimace':
                emotion = '鬼脸'
            data_people['emotion'] = emotion
            face_type = content['result']['face_list'][0]['face_type']['type']
            # human: 真实人脸 cartoon: 卡通人脸
            if face_type == 'human':
                face_type = '真实人脸'
            elif face_type == 'cartoon':
                face_type = '卡通人脸'
            data_people['face_type'] = face_type

            write(data_people['age'], 758, 193)
            write(data_people['expression'], 760, 265)
            write(data_people['face_shape'], 760, 341)
            write(data_people['gender'], 764, 418)
            write(data_people['glasses'], 874, 492)
            write(data_people['emotion'], 762, 564)
            write(data_people['face_type'], 1024, 645)
            showPhoto(photo, 16, 19)

# 创建选择图片按钮
choose_imageLabel = tk.Button(window, image=choose_image_button, bd=0, command=select_photo)
choose_imageLabel.place(x=1200, y=620)

# 屏幕刷新
window.mainloop()
